(function($) {

	$.fn.inline = function(options){

		var defaults = {
			url : "ajax.php", //url for ajax request
			title : true, //for db table_name
			textarea : false //set up textarea mode for all inline item
		},
		settings = $.extend(defaults, options);
		
		return this.each(function(){
			obj = $(this); //reference to this

			obj.find(".item").each(function(){
				var id = $(this).attr("id"), // for item-id
					type = $(this).attr("rel"), // for single textarea mode
					$item = $(this); //reference for current div.item
				
				$item.find("span").click(function(){
					if($('.inline_form').size()){
						return false; //return false if another .inline_form already opened
					}
					
					var itemId = id.substr(id.indexOf("-")+1), //get item_id (unique key)
					value = $(this).html(); //get the current value
					
					//hide span
					$(this).hide(); //hide value
					
					//append form to inline item
					$item.append(
						'<form method="post" action="'+ settings.url +'" class="inline_form">'+
						' <input type="hidden" name="item-id" value="'+ itemId +'" />'+
						' <input type="Submit" value="Update" />'+
						' <a href="javascript:void();" class="cancel">Cancel</a></form>'
					);

					//switch title mode
					if(settings.title == true){
						$item.find('.inline_form')
						.prepend('<input type="hidden" name="field" value="'+ $item.attr("title") +'" />');
					}

					//switch textarea mode
					if(settings.textarea || type == "textarea"){
						$item.find('.inline_form')
						.prepend('<textarea name="data">'+ value +'</textarea><br />');
						$item.find('textarea').focus();
					}else{
						$item.find('.inline_form')
						.prepend('<input type="text" name="data" value="'+ value +'" />');
						$item.find('input[type="text"]').focus();
					}

					//remove form
					$item.find('.cancel').each(function(){
						$(this).click(function(){
							$item.find("span").fadeIn(400);
							$(this).parent().remove();
						});
					});
					//key = escape
					$(document).keyup(function(event){
						if(event.keyCode == 27) {
							$item.find("span").fadeIn(400);
							$(".inline_form").remove();
						}
					});
					
					//AJAX submit
					$item.find('.inline_form').submit(function(){
						$.ajax({
							type: 'POST',
							url: settings.url,
							data: $(this).serialize(),
							success: function(data) {
								$item.find('.inline_form').remove();
								$item.find("span").css("color","#666").html(data).fadeIn(400);
							},
							error: function() {
								alert("ajax error!");
							}
						})
						return false;
					});
					
				});
				
			});
			
		});
		
	}
	
} ) (jQuery);